package com.hmdp.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.pro.model.UserModel;
import com.hmdp.pro.model.UserModelDraft;
import com.hmdp.pro.model.UserModelTable;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.babyfish.jimmer.sql.JSqlClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 七倉玲華
 * @since 2022-10-30
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final JSqlClient sqlClient;
    private final StringRedisTemplate redisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }
        String code = RandomUtil.randomNumbers(6);
        //session.setAttribute("code", code);
        redisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        // example: 13456789001
        log.debug("验证码发送成功，验证码：{}", code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }
//        Object cacheCode = session.getAttribute("code");
        String cacheCode = redisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (cacheCode == null || !Objects.equals(cacheCode, loginForm.getCode())) {
            return Result.fail("验证码错误");
        }
        UserModelTable t = UserModelTable.$;
        UserModel userModel = sqlClient.createQuery(t).where(t.phone().eq(phone)).select(t).execute().get(0);
        if (userModel == null) {
            userModel = createUserWithPhone(phone);
        }
        String token = UUID.randomUUID().toString(true);
        String tokenKey = LOGIN_USER_KEY + token;
        // 要注意StringRedisTemplate默认使用的是 Map<String, String>
        redisTemplate.opsForHash().putAll(tokenKey,
                MapUtil.builder(new HashMap<String, String>())
                        .put("id", Long.toString(userModel.id()))
                        .put("icon", userModel.icon())
                        .put("nickname", userModel.nickName())
                        .build()
        );
        redisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    private UserModel createUserWithPhone(String phone) {
        return sqlClient.getEntities().save(UserModelDraft.$.produce(user -> user
                .setPhone(phone)
                .setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(9)))).getModifiedEntity();
    }
}
